<?php
/**
 * 微信SDK
 * pan041ymail@gmail.com
 */

namespace app\store\controller;

vendor('qiniu.autoload');

use Qiniu\Auth;
use Qiniu\Storage\BucketManager;
use Qiniu\Processing\PersistentFop;


use think\Db;
use think\Exception;

class Weixin
{
    public $appid = "";
    public $appsecret = "";
    public $access_token = "";

    /**
     * 构造函数
     */
    public function __construct($shop_id,$appid = NULL, $appsecret = NULL)
    {
        // $wxConfig = config('weixin');
        // $res = Db::name('option')->where('option_name', 'wx')->find();
        // $wxConfig=json_decode($res['option_value'],true);

        // 获取对应店铺的微信配置信息
        $wxConfig = Db::name('shops')->where('shop_id',$shop_id)->find();

        $this->appsecret    = $wxConfig['appsecret'];
        $this->appid        = $wxConfig['appid'];
        $this->shop_id      = $shop_id;

        if ($appid) {
            $this->appid = $appid;
        }
        if ($appsecret) {
            $this->appsecret = $appsecret;
        }

    }

    /**
     * 发送模板消息
     * $openid              接收者openid       oTJius6kQ2hFOF66Dw0l5Xg-ICUM
     * $template_id         模板ID             BWrP-c1uXNvLvO-YNDtbVGVd0iiP7O3LibkzXkHirTI
     * $url                 详情跳转地址        http://www.qq.com

     * $data_arr            数据体             数组
     */
    public function sentMsg($openid, $template_id , $url = '' , $data_arr=[])
    {
        // 获取access_token
        $access_token = $this->getAccessToken();

        // 接口地址
        $api = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $access_token;

        // 模板参数
        $data['touser']         = $openid;
        $data['template_id']    = $template_id;
        $data['url']            = $url;

        // 模板数据
        $data['data']           = $data_arr;

        // 转json类型
        $data = json_encode($data);

        // 发送消息
        $res = $this->https_request($api, $data);
        $res = json_decode($res, true);
        if ($res['errcode'] != 0) {
            session('access_token', false);
        }

        return $res;
    }

    public function sendparent($open_id,$url,$user_name){
        $temp_id=   Db::name('option')->where('option_name','sendp_temp')->value('option_value');
        $access_token = $this->getAccessToken();
        $api = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={$access_token}";
        $data['touser'] = $open_id;
        $data['template_id'] = $temp_id;
//        $data['url'] = request()->domain() . $url;
        $data['url'] = '';
        $data_arr = [];
        $data_arr['first'] = ['value' => '您好，亲爱的家长', 'color' => '#173177'];
        $data_arr['keyword1'] = ['value' => $user_name['value'], 'color' => '#173177'];
        $data_arr['remark'] = ['value' => '此为提示信息,请以实际情况为准。', 'color' => '#173177'];
        $data['data'] = $data_arr;
        $data = json_encode($data);
        $res = $this->https_request($api, $data);
        $res = json_decode($res, true);
        dump($res);
        if ($res['errcode'] == 0) {
            return true;
        }
        return false;
    }

    /**
     * 获取AccessToken
     */
    public function getAccessToken()
    {
        // $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appid}&secret={$this->appsecret}";
        // $res = $this->https_request($url);
        // $res = json_decode($res, true);
        // dump($res);die;

        $token = false;

        // 是否已存有AccessToken信息
        $acc_token = Db::name('shops')->where('shop_id', $this->shop_id)->find();

        if ($acc_token && $acc_token['access_token_time'] > time()) {

            $token = $acc_token['access_token'];

        } else {

            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appid}&secret={$this->appsecret}";
            $res = $this->https_request($url);
            $res = json_decode($res, true);
            // dump($res);

            try {
                // 更新数据库配置信息
                if ($res['access_token']) {

                    $update = [];

                    $update['access_token']         = $res['access_token'];
                    $update['access_token_time']    = time() + 7000;

                    Db::name('shops')->where('shop_id', $this->shop_id)->update($update);

                    $token = $res['access_token'];
                }

            } catch (Exception $exception) {

            }
        }

        return $token;

    }


    /**
     * 获取ticket
     */
    public function getTicket()
    {
        $this->access_token = $this->getAccessToken();
        if (!$this->access_token) {
            echo 'access_token error';
            die;
        }

        $jsapi_ticket = false;

        $ticket = Db::name('shops')->where('shop_id', $this->shop_id)->find();

        if ($ticket && $ticket['ticket_time'] > time()) {

            $jsapi_ticket = $ticket['ticket'];

        } else {

            $tick_url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=$this->access_token&type=jsapi";
            $res = $this->https_request($tick_url);

            /*
             * 返回数据格式
             {
                "errcode":0,
                "errmsg":"ok",
                "ticket":"bxLdikRXVbTPdHSM05e5u5sUoXNKd8-41ZO3MhKoyN5OfkWITDGgnr2fwJ0m9E8NYzWKVZvdVtaUgWvsdshFKA",
                "expires_in":7200
            }*/

            //获取JS_TICKET
            $res = json_decode($res, true);

            try {

                if ($res['errmsg'] == 0) {

                    $update = [];

                    $update['ticket']       = $res['ticket'];
                    $update['ticket_time']  = time() + 7000;

                    // session('ticket', $update);

                    Db::name('shops')->where('shop_id', $this->shop_id)->update($update);

                    $jsapi_ticket = $res['ticket'];
                }

            } catch (Exception $exception) {

            }
        }

        return $jsapi_ticket;

    }




    /*
     * 获取临时的文件
     */
    //$b = "1";
    //if($b == "1"){
    //$id = "Zary6julqwRBBuSgzFbiMCSjYmG2930UvzjrbnHN4nyT3YGZVD8H-ecfoReGT1Qr";
    //$url = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=".token()."&media_id=".$id;
    //$arr = downloadWeixinFile($url);
    //saveWeixinFile("1.jpg",$arr['body']);
    //
    //}
    public function getTempVoice($id)
    {
        $this->access_token = $this->getAccessToken();

        $url = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=" . $this->access_token . "&media_id=" . $id;

        //使用七牛抓取
        $qnConfig = config('qiniu');

        $accessKey  = $qnConfig['ak'];
        $secretKey  = $qnConfig['sk'];
        $bucket     = $qnConfig['bk'];

        $auth           = new Auth($accessKey, $secretKey);
        $bucketManager  = new BucketManager($auth);

        $key_name   = date('Ymd',time()).'/'.$id;
        $key        = $key_name. '.amr';

        // 指定抓取的文件保存名称
        list($err) = $bucketManager->fetch($url, $bucket, $key);
        // echo "=====> fetch $url to bucket: $bucket  key: $key\n";
        if ($err !== null) {
        // var_dump($err);
        // 转码
        // $auth = new Auth($accessKey, $secretKey);

        // 要转码的文件所在的空间和文件名。
        // $key = $key;

        // 转码是使用的队列名称。 https://portal.qiniu.com/mps/pipeline
            $pipeline = 'qimeng';

        // 转码完成后通知到你的业务服务器。
        // $notifyUrl = 'http://375dec79.ngrok.com/notify.php';
        // $notifyUrl = url('index/api/voicenotify');
        // $notifyUrl = 'http://wx007.imwork.net/index/api/voicenotify';

        $notifyUrl = request()->domain().'/index/api/voicenotify';
        $force = false;

        $config = new \Qiniu\Config();
        $config->useHTTPS = true;
        $pfop = new PersistentFop($auth, $config);

        // 要进行视频截图操作

        $fops = "avthumb/mp3/ab/128k/ar/44100/acodec/libmp3lame|saveas/" . \Qiniu\base64_urlSafeEncode($bucket . ":$key_name.mp3");

        list($id, $err2) = $pfop->execute($bucket, $key, $fops, $pipeline, $notifyUrl, $force);

            return $err['key'];
        } else {

            return false;
        }

        $arr = $this->downloadWeixinFile($url);
        $file_name = time() . rand(0000, 9999) . '.amr';
        return $this->saveWeixinFile($file_name, $arr['body']);

    }


    public function getTempFile($id)
    {
        $this->access_token = $this->getAccessToken();
        $url = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=" . $this->access_token . "&media_id=" . $id;

        $qn_config = Db::name('option')->where('option_name', 'qiniu')->value('option_value');
        $qn_config = json_decode($qn_config, true);
        //使用七牛抓取
        $accessKey = $qn_config['ak'];
        $secretKey = $qn_config['sk'];
        $bucket = $qn_config['bk'];
        // $domain = $qnConfig['domain'];


        $auth = new Auth($accessKey, $secretKey);
        $bucketManager = new BucketManager($auth);


        $key = date('Ymd',time()).'/'.$id. '.jpg';

        // 指定抓取的文件保存名称
        list($err) = $bucketManager->fetch($url, $bucket, $key);
        // echo "=====> fetch $url to bucket: $bucket  key: $key\n";
        if ($err !== null) {

            // 七牛样式处理
            $q_thumb    = "?imageMogr2/auto-orient/thumbnail/!60x120r/gravity/Center/crop/60x80/quality/100/interlace/0";
            $f_name     = $err['key'];
            $f_name2    = $qn_config['domain'] . '/' . $f_name . $q_thumb;

            return ['url'=>$f_name2,'src'=>$f_name];
        } else {

            return false;
        }


    }

    public function getTempFile2($id)
    {
        $this->access_token = $this->getAccessToken();
        $url = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=" . $this->access_token . "&media_id=" . $id;

        $qn_config = Db::name('option')->where('option_name', 'qiniu')->value('option_value');
        $qn_config = json_decode($qn_config, true);
        //使用七牛抓取
        $accessKey = $qn_config['ak'];
        $secretKey = $qn_config['sk'];
        $bucket = $qn_config['bk'];
        // $domain = $qnConfig['domain'];


        $auth = new Auth($accessKey, $secretKey);
        $bucketManager = new BucketManager($auth);


        $key = date('Ymd',time()).'/'.$id. '.jpg';

        // 指定抓取的文件保存名称
        list($err) = $bucketManager->fetch($url, $bucket, $key);
        // echo "=====> fetch $url to bucket: $bucket  key: $key\n";
        if ($err !== null) {

            // 七牛样式处理
            $q_thumb    = "?imageMogr2/auto-orient/thumbnail/!60x120r/gravity/Center/crop/60x80/quality/100/interlace/0";
            $f_name     = $err['key'];
            $f_name2    = $qn_config['domain'] . '/' . $f_name . $q_thumb;
            $f_name3    = $qn_config['domain'] . '/' . $f_name ;

            return ['url'=>$f_name2,'src'=>$f_name3];
        } else {

            return false;
        }


    }


    public function downloadWeixinFile($url)
    {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_NOBODY, 0);    //只取body头
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $package = curl_exec($ch);
        $httpinfo = curl_getinfo($ch);
        curl_close($ch);
        $imageAll = array_merge(array('header' => $httpinfo), array('body' => $package));
        return $imageAll;
    }


    public function saveWeixinFile2($filecontent)
    {
        $filename2 = $filename = time() . rand(0000, 9999) . '.jpg';

        //动态的创建一个文件夹
        $path       = date('Ymd');
        $save_path  = $_SERVER['DOCUMENT_ROOT'] . "/live/" . $path;

        //判断该文件夹是否已经有这个文件夹
        if (!file_exists($save_path)) {
            mkdir($save_path);
        }

        $filename=$save_path . '/' . $filename;

        try {

            $local_file = fopen($filename, 'w');

            if (false !== $local_file) {

                if (false !== fwrite($local_file, $filecontent)) {

                    fclose($local_file);
                }

            }

            return '/live/' . $path . '/' . $filename2;

        } catch (Exception $exception) {

            return false;
        }


        return false;

    }



    /**
     * jsApi配置文件
     */
    public function js_config($url)
    {
        $jsapi_ticket = $this->getTicket();
        if (!$jsapi_ticket) {
            echo 'ticket error';
            die;
        }

        // noncestr=Wm3WZYTPz0wzccnW
        // jsapi_ticket=sM4AOVdWfPE4DxkXGEs8VMCPGGVi4C3VM0P37wVUCFvkVAy_90u5h9nbSlYy3-Sl-HhTdfl2fzFy1AOcHKP7qg
        // timestamp=1414587457
        // url=http://mp.weixin.qq.com?params=value

        $noncestr   = "Wm3WZYTPz0wz" . rand(0000, 9999);
        $timestamp  = time();

        $sha1_str   = "jsapi_ticket=$jsapi_ticket&noncestr=$noncestr&timestamp=$timestamp&url=$url";
        $signature  = sha1($sha1_str);

        $config = [];

        $config['timestamp']    = $timestamp;
        $config['noncestr']     = $noncestr;
        $config['signature']    = $signature;
        $config['appId']        = $this->appid;

        return $config;

    }


    /**
     * 获取用户基本信息
     */
    public function get_user_info($openid)
    {
        $this->access_token = $this->getAccessToken();

        $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" . $this->access_token . "&openid=" . $openid . "&lang=zh_CN";

        $res = $this->https_request($url);

        return json_decode($res, true);
    }

    /**
     * https请求
     */
    public function https_request($url, $data = null)
    {
        $curl = curl_init();

        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);

        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }

        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

        $output = curl_exec($curl);

        curl_close($curl);

        return $output;
    }
}